package com.example.carconsumer.controller.dl.admin;

import com.alibaba.dubbo.config.annotation.Reference;
import com.example.carinterface.pojo.OwnerCard;
import com.example.carinterface.service.dl.admin.CustomerService;
import com.example.carinterface.service.dl.admin.OwnerCardService1;
import com.example.carinterface.service.hkf.OwnerCardService;
import com.example.carinterface.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@CrossOrigin
@RestController
@RequestMapping("/admin/customer")
@Api(tags = "admin - 客户管理")
public class CustomerController {

    @Reference(check = false)
    private CustomerService customerService;
    @Reference(check = false)
    OwnerCardService1 ownerCardService1;

    @PostMapping("/findCustomer")
    @ApiOperation("用户管理列表")
    public ResultJson<List<Map<String, Object>>> findCustomer(@ApiParam(value = "不传查全部，name:用户名，或者，" +
            "tel:手机号," +
            "id:用户id") @RequestBody(required = false) Map<String, String> map) {

        return customerService.findCustomer(map);
    }

    @PostMapping("/addCustomer")
    @ApiOperation("添加用户")
    public ResultJson<String> addCustomer(@ApiParam("name:联系人，" +
            "tel:联系电话，" +
            "idCard:身份证号，" +
            "remarks:备注") @RequestBody Map<String, Object> map) {

        return customerService.addCustomer(map);
    }

    @PostMapping("/updateCustomer")
    @ApiOperation("修改用户")
    public ResultJson<String> updateCustomer(@ApiParam("id:用户id，" +
            "name:联系人，" +
            "tel:联系电话，" +
            "idCard:身份证号，" +
            "remarks:备注") @RequestBody Map<String, Object> map) {

        return customerService.updateCustomer(map);
    }

    //-------------------------------------------------------------------------------

    @PostMapping("/intsertOwnerCard")
    @ApiOperation(value = "添加车主卡", responseReference = "添加车主卡信息", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectOwnerCard(@ApiParam(name = "ownerCard", value = "车主卡的信息", required = true) OwnerCard ownerCard,
                                      @ApiParam(name = "file", value = "行驶证照片", required = false) MultipartFile file,
                                      HttpServletRequest request) {
        ResultJson resultJson = new ResultJson();
        System.out.println(ownerCard);
        if (file == null) {
            if (ownerCardService1.insertOwnerCard(ownerCard) > 0) {
                return resultJson.setSuccess("修改成功");
            } else {
                return resultJson.setFail("修改失败");
            }
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String res = sdf.format(new Date());
            String name = ownerCard.getOwnerName();
            // uploads文件夹位置
            String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//        String rootPath = request.getSession().getServletContext().getRealPath("download/drivingLicense/");
            // 原始名称
            String originalFileName = file.getOriginalFilename();
            String substring = originalFileName.substring(originalFileName.lastIndexOf("."));//后缀名
            if (substring.equals(".jpg") || substring.equals(".png")) {
                // 新文件名
                String newFileName = name + res + substring;
                // 创建年月文件夹
                Calendar date = Calendar.getInstance();
                File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));

                // 新文件
                File newFile = new File(rootPath + "/download/drivingLicense/" + File.separator + dateDirs + File.separator + newFileName);
                // 判断目标文件所在目录是否存在
                if (!newFile.getParentFile().exists()) {
                    // 如果目标文件所在的目录不存在，则创建父目录
                    newFile.getParentFile().mkdirs();
                }


                // 将内存中的数据写入磁盘
                try {
                    file.transferTo(newFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }


                ownerCard.setDrivingLicenseUrl("download\\drivingLicense" + File.separator + dateDirs + File.separator + newFileName);
                System.out.println("download" + File.separator + dateDirs + File.separator + newFileName);
                if (ownerCardService1.insertOwnerCard(ownerCard) > 0) {
                    return resultJson.setSuccess("修改成功");
                } else {
                    return resultJson.setFail("修改失败");
                }
            } else {
                return resultJson.setFail("添加失败,图片文件格式错误");
            }
        }


    }

    @GetMapping("/selectOwnerCard")
    @ApiOperation(value = "查询我的车主卡", responseReference = "查询我的车主卡信息", httpMethod = "post", response = ResultJson.class)
    public ResultJson<List> selectOwnerCard(@ApiParam(name = "userId", value = "当前用户的id", required = true) Integer userId) {
        return ownerCardService1.selectOwnerCard(userId);
    }

    //-----------------------------------------------------------------------------------------

    @PostMapping("/updateOwnerCard")
    @ApiOperation("修改车主卡")
    public ResultJson<String> updateOwnerCard(@ApiParam("userId:持卡人id," +
            "tel:联系电话," +
            "id:车主卡id") @RequestBody Map<String, Object> map) {

        return customerService.updateOwnerCard(map);
    }


    //
    @PostMapping("/findBrand")
    @ApiOperation("查询所有品牌和型号")
    public ResultJson<List<Map<String, Object>>> findBrand(
            @ApiParam("name:品牌名（可不传）")
            @RequestBody(required = false) Map<String,Object> map) {
        return customerService.findBrand(map);
    }
    @PostMapping("/findCarModel/{id}")
    @ApiOperation("通过品牌型号id查询具体型号")
    public ResultJson<List<Map<String,Object>>> findCarModel(@ApiParam("id:id") @PathVariable("id") Integer id){

        return customerService.findCarModel(id);

    }



    //司机管理
    //司机界面
    @PostMapping("/findDriver")
    @ApiOperation("查询司机")
    public ResultJson<List<Map<String, Object>>> findDriver(@ApiParam("不传查全部。司机姓名(？？)或者手机号：condition ") @RequestBody(required = false) Map<String, Object> map) {

        return customerService.findDriver(map);
    }

    //上传司机照片
    @PostMapping("/uploadDriverHeadImg")
    @ApiOperation("上传司机照片")
    public ResultJson<String> uploadImgUrl(MultipartFile file, HttpServletRequest request) {

        System.out.println("开始上传");
        //上传路径
        String uploadFile = "";
        try {
            uploadFile = ResourceUtils.getURL("classpath:").getPath()+"static/upload/driver";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        //获取文件名
        String fileName = file.getOriginalFilename();
        //唯一文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        fileName = uuid + "_" + fileName;

        File file0 = new File(uploadFile);
        file0.mkdirs();

        //保存文件
        try {
            file.transferTo(new File(uploadFile , fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        ResultJson<String> resultJson = new ResultJson<>();
        resultJson.setSuccess("上传成功",uploadFile+ fileName, 1L);

        return resultJson;
    }



    //添加司机
    @PostMapping("/addDriver")
    @ApiOperation("添加司机")
    public ResultJson<String> addDriver(@ApiParam("name:司机姓名，" +
            "carNumber：车牌号，" +
            "tel：联系电话，" +
            "password：登录密码，" +
            "idCard：身份证号，" +
            "region：所在区域，" +
            "headImg：头像地址，" +
            "state：在职状态：-1离职，1在职") @RequestBody Map<String, Object> map) {

        String password = map.get("password").toString();
        SimpleHash simpleHash = new SimpleHash("md5", password, map.get("tel").toString(), 32);

        map.put("password",simpleHash.toString());
        return customerService.addDriver(map);

    }

    //修改司机
    @PostMapping("/updateDriver")
    @ApiOperation("修改司机")
    public ResultJson<String> updateDriver(@ApiParam("id：id，" +
            "idCard：身份证号，" +
            "region：所在区域，" +
            "tel：手机号，" +
            "state：状态：-1离职，1在职，" +
            "carNumber：车牌号，" +
            "headImg：照片地址，" +
            "password：密码，" +
            "name:姓名") @RequestBody Map<String,Object> map){

        String password = map.get("password").toString();
        SimpleHash simpleHash = new SimpleHash("md5", password, map.get("tel").toString(), 32);

        map.put("password",simpleHash.toString());
        return customerService.updateDriver(map);
    }
}